// 防止表单回车直接跳转页面
document.onkeydown = function (event) {
    var target, code, tag;
    if (event) {
        target = event.target; //针对遵循w3c标准的浏览器，如Firefox
        code = event.keyCode;
        if (code == 13) {
            tag = target.tagName;
            if (tag == "INPUT") {
                $('.ajax-post').trigger("click");
                return false;
            } else {
                return true;
            }
        }
    }
};

// 筛选
$('.screen-btn').click(function () {
    var pathname = window.location.pathname.replace('.html', '').split('/');
    var url = window.location.pathname.replace('.html', '');

    pathname.splice(0, 4);
    var param_name_arr = [];
    pathname.forEach(function ($v, $k) {
        if ($k % 2 == 0 && param_name_arr.indexOf($v) == -1) param_name_arr.push($v);
    })

    var input_param = $('.search-form').find('input').length > 0 ? $('.search-form').find('input').serialize().split('&') : [];
    var select_param = $('.search-form').find('select').length > 0 ? $('.search-form').find('select').serialize().split('&') : [];

    if (input_param) {
        input_param.forEach(function (val) {
            var param = val.split('=');
            if (param[1] !== '') {
                if (param_name_arr.indexOf(param[0]) == -1) {
                    url += '/' + param[0] + '/' + param[1];
                } else {
                    var url_arr = url.split('/');
                    var param_index = url_arr.indexOf(param[0]);
                    var search_url_str = url_arr[param_index] + '/' + url_arr[param_index + 1];
                    var replace_url_str = url_arr[param_index] + '/' + param[1];

                    url = url.replace(search_url_str, replace_url_str);
                }
            } else {
                var url_arr = url.split('/');
                var param_index = url_arr.indexOf(param[0]);
                var search_url_str = '/' + url_arr[param_index] + '/' + url_arr[param_index + 1];

                url = url.replace(search_url_str, '');
            }
        });
    }

    if (select_param) {
        select_param.forEach(function (val) {
            var param = val.split('=');
            if (param[1] !== '') {
                if (param_name_arr.indexOf(param[0]) == -1) {
                    url += '/' + param[0] + '/' + param[1];
                } else {
                    var url_arr = url.split('/');
                    var param_index = url_arr.indexOf(param[0]);
                    var search_url_str = url_arr[param_index] + '/' + url_arr[param_index + 1];
                    var replace_url_str = url_arr[param_index] + '/' + param[1];

                    url = url.replace(search_url_str, replace_url_str);
                }
            } else {
                var url_arr = url.split('/');
                var param_index = url_arr.indexOf(param[0]);
                var search_url_str = '/' + url_arr[param_index] + '/' + url_arr[param_index + 1];

                url = url.replace(search_url_str, '');
            }
        });
    }

    window.location.href = url + '.html';
})

// 导出
$('.excel-btn').click(function () {
    var pathname = window.location.pathname;
    var pathname_arr = pathname.split("/");
    var replace_str = '/' + pathname_arr[1] + '/' + pathname_arr[2] + '/' + pathname_arr[3];
    var to_replace_str = '/' + pathname_arr[1] + '/' + pathname_arr[2] + '/' + 'export' + pathname_arr[3].charAt(0).toUpperCase() + pathname_arr[3].slice(1);
    var url = pathname.replace(replace_str, to_replace_str);

    window.location.href = url;
})

// 列表全选
$('.check-all').click(function () {
    var is_check = $(this).prop('checked');
    $('.check-single').prop('checked', is_check);
})

// 列表单选
$('.check-single').click(function () {
    var is_check = $(this).prop('checked');
    if (is_check) {
        var all_checkbox_count = $('.check-single').length;
        var check_count = $('.check-single:checked').length;
        if (all_checkbox_count == check_count) {
            // 全部选中
            $('.check-all').prop('checked', true);
        } else {
            // 未全部选中
            $('.check-all').prop('checked', false);
        }
    } else {
        $('.check-all').prop('checked', false);
    }
})

// 一键删除
$('.all-delete-btn').click(function () {
    // 数据库名称（不带前缀）
    var param = $(this).data('param');
    if (!param) {
        layer.msg('一键删除所需参数缺失，请联系后台开发人员');
    } else {
        var check_ids = [];
        $('.check-single:checked').each(function () {
            var id = $(this).val();
            check_ids.push(id);
        })
        if (check_ids.length) {
            swal({
                title: '您确认删除吗？',
                type: "warning",
                cancelButtonText: '取消',
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                closeOnConfirm: false
            }, function () {
                // 加载层
                var index = layer.load(2, {shade: [0.2, '#000']});
                $.get('/action/Common/listDataAllDelete', {
                    param: param,
                    check_ids: check_ids.join(',')
                }, function (res) {
                    if (res.result == 1) {
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000)
                    } else if (res.result == 2) {
                        layer.close(index);
                        layer.msg(res.msg);
                    }
                }, 'json');

                setTimeout(function () {
                    layer.close(index);
                }, 3000)
            });
        } else {
            layer.msg('请勾选您需要删除的数据');
        }
    }
})


// 表单提交
$('.ajax-post').click(function () {
    //加载层
    var index = layer.load(2, {shade: [0.2, '#000']});

    var action = $(this).parents().attr("action");
    if (!action) {
        var url = window.location.href;
    } else {
        //取出第一个字符
        var first = action.slice(0, 1);
        if (first == '/') {
            var url = action;
        } else {
            var url = '/' + action
        }
    }

    //判断表单中是否使用了kindEditor
    var haveKindEditor = false;
    var editorName = '';
    for (var i = 0; i < $("textarea").length; i++) {
        var textareaElement = $("textarea")[i];
        if ($(textareaElement).data('editor') == 'kindEditor') {
            haveKindEditor = true;
            editorName = $(textareaElement).attr("name");
            break;
        }
    }
    if (haveKindEditor && editorName == '') {
        layer.close(index);
        layer.msg('富文本隐藏域缺少name属性');
        return;
    } else if (haveKindEditor && editorName) {
        window.editor.sync();
        //将富文本中的内容赋值到textarea隐藏域中以供表单提交
        $('textarea[name="' + editorName + '"]').val($('#' + kindEditorID).val());
    }

    var formData = $('form').serialize();
    $.post(url, formData, function (res) {
        if (res.result == 1) {
            setTimeout(function () {
                window.location.href = res.url;
            }, res.timer)
        } else if (res.result == 2) {
            layer.close(index);
            layer.msg(res.msg);
        } else if (res.result == 3) {
            layer.close(index);
            layer.msg(res.msg);
            //后台登录失败，需要刷新【表单令牌】和【验证码】
            if (res.token) $("[name='__token__']").val(res.token);
            $('#captcha').attr('src', "/captcha.html?" + Math.random())
        }
    }, 'json');

    setTimeout(function () {
        layer.close(index);
    }, 3000)
    return false;
});

// 初始化KindEditor富文本编辑器
var kindEditorID;

function initKindEditor(editor_id, width = 710, height = 500, items = ['source', 'undo', 'redo', '|', 'preview', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'clearhtml', '|', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'link', 'unlink', '|', 'fullscreen']) {
    if (!editor_id) {
        layer.close();
        layer.msg('调用initKindEditor方法缺少富文本ID参数');
        return;
    } else {
        kindEditorID = editor_id;
    }

    KindEditor.ready(function (K) {
        window.editor = K.create('#' + editor_id, {
            width: width,
            height: height,
            items: items
        });
    });
}

// 删除
$('.ajax-del').click(function () {
    var msg = $(this).data('msg') ? $(this).data('msg') : '您确认删除吗？';
    var url = $(this).attr("href");

    swal({
        title: msg,
        type: "warning",
        cancelButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        closeOnConfirm: false
    }, function () {
        // 加载层
        var index = layer.load(2, {shade: [0.2, '#000']});

        $.get(url, function (res) {
            if (res.result == 1) {
                setTimeout(function () {
                    window.location.reload();
                }, res.timer)
            } else if (res.result == 2) {
                layer.close(index);
                layer.msg(res.msg);
            }
        }, 'json');

        setTimeout(function () {
            layer.close(index);
        }, 3000)
    });
    return false;
})

// 操作
$('.ajax-operate').click(function () {
    var url = $(this).attr("href");

    swal({
        title: "您确认要执行该操作吗？",
        type: "warning",
        cancelButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: "#1BBF80",
        confirmButtonText: "确认",
        closeOnConfirm: false
    }, function () {
        // 加载层
        var index = layer.load(2, {shade: [0.2, '#000']});

        $.get(url, function (res) {
            if (res.result == 1) {
                setTimeout(function () {
                    window.location.href = res.url;
                }, res.timer)
            } else if (res.result == 2) {
                layer.close(index);
                layer.msg(res.msg);
            }
        }, 'json');

        setTimeout(function () {
            layer.close(index);
        }, 3000)
    });
    return false;
})

// 返回上一页
$('.back-page').click(function () {
    window.history.go(-1);
})

// 清理缓存
$('#clear-cache').click(function () {
    var url = "/admin/Func/clearCache";
    $.post(url, function () {
        layer.msg('缓存清理成功')
    }, 'json')
})

// 退出登录
$('#logout').click(function () {
    var url = "/admin/Func/logout";
    $.post(url, function (res) {
        layer.msg(res.msg)
        setTimeout(function () {
            window.location.href = res.data;
        }, res.timer)
    }, 'json')
})

// 修改密码
$('#confirmUpdateAdminPwd').click(function () {
    var old_admin_pwd = $('.old_admin_pwd').val();
    var new_admin_pwd = $('.new_admin_pwd').val();
    var re_admin_pwd = $('.re_admin_pwd').val();

    if (!old_admin_pwd) {
        layer.msg('请输入原密码');
        return;
    }
    if (!new_admin_pwd) {
        layer.msg('请输入新密码');
        return;
    }
    if (!re_admin_pwd) {
        layer.msg('请输入确认密码');
        return;
    }
    if (new_admin_pwd !== re_admin_pwd) {
        layer.msg('两次密码不一致，请重新输入');
        return;
    }

    var url = "/admin/func/updateAdminPwd";

    $.post(url, {
        old_admin_pwd: old_admin_pwd,
        new_admin_pwd: new_admin_pwd
    }, function (res) {
        layer.msg(res.msg)
        if (res.result == 1) {
            $(".close-model").trigger("click");
        }
    }, 'json')
})

/**
 * 清空 input file
 * @param {string} id file上传按钮id
 * */
function clearFile(id) {
    var file = $("#" + id);
    file.after(file.clone().val(""));
    file.remove();
}

/**
 * 单图上传
 * @param    file_id        file上传按钮id
 * @param    img            图片id隐藏域
 * @param    img_btn        图片上传按钮id
 * */
function uploadImg(file_id, img, img_btn) {
    $("#" + file_id).trigger("click");
    $('#' + file_id).change(function () {
        var pic = $(this)[0].files[0];
        var formData = new FormData();
        var url = "/Upload/UploadFile/uploadPicture";
        formData.append('download', pic);
        $.ajax({
            url: url,
            type: "post",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.status == 1) {
                    clearFile(file_id);

                    //上传成功
                    var id = data.data.id;
                    var path = data.data.path;

                    $('#' + img).val(id);
                    $('#' + img_btn).attr('src', path);
                } else {
                    layer.msg(data.info);
                }
            }
        });
    });
}

/**
 * 多图上传
 * @param    file_id        file上传按钮id
 * @param    imgs            图片id隐藏域
 * @param    imgs_div        已上传图片盒子id
 * */
function uploadImgs(file_id, imgs, imgs_div) {
    $("#" + file_id).trigger("click");

    $("#" + file_id).change(function () {
        var pics = $(this)[0].files;

        for (var i = 0; i < pics.length; i++) {
            var formData = new FormData();
            var url = "/upload/UploadFile/uploadPicture";
            formData.append('download', pics[i]);
            $.ajax({
                url: url,
                type: "post",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    if (data.status == 1) {
                        clearFile(file_id);

                        var img_ids = $('#' + imgs).val();

                        //上传成功
                        var id = data.data.id;
                        var path = data.data.path;

                        var img_str = '<div class="upload-files-div"><img class="upload-files" src="' + path + '" /><span class="upload-file-del" onclick="delThisPic(this)">删除</span></div>';
                        $('#' + imgs_div).append(img_str)

                        if (img_ids == '') {
                            img_ids = id;
                        } else {
                            img_ids += ',' + id;
                        }
                        $('#' + imgs).val(img_ids)
                        $('#' + file_id).val('');
                    }
                }
            });
        }
    });
}

// 删除图片（老版本）
function delThisPic(that) {
    var index = $('.upload-file-del').index(that);
    var imgs = $('#imgs').val();
    var imgs_arr = imgs.split(',')

    //按某个字符切割字符串成数组
    imgs_arr.splice(index, 1);
    //数组转换字符串
    imgs = imgs_arr.join(',');

    $('#imgs').val(imgs);
    $(that).parent().remove();
}

/**
 * 渲染预览图
 * @param {number} id 图片id
 * @param {string} path 图片路径
 * @param {string} preview_id  已上传图片预览盒子id
 * @param {boolean} is_cropper 是否是裁剪框中的预览图
 * @param {number} max_upload_count 最多上传图片数量
 * */
function renderPreviewImg(id, path, preview_id, is_cropper = false, max_upload_count = 9) {
    var prefix = !is_cropper ? 'form-' : '';
    var img_html = `<div class="` + prefix + `uploaded-img-box">
                            <img class="` + prefix + `uploaded-box-img" src="` + path + `" data-id="` + id + `">
                            <i class="` + prefix + `uploaded-img-preview iconfont icon-yulan" onclick="previewImg(this, '` + prefix + `uploaded-img-preview')"></i>
                            <i class="` + prefix + `uploaded-img-del iconfont icon-close" onclick="delImage(this, 'cropper_uploaded_img_ids', 'cropper_uploaded_img_paths', '` + prefix + `')"></i>
                        </div>`;

    var uploaded_count = $('#' + preview_id).find('img').length;

    if (max_upload_count == 1) {
        // 单图上传
        $('#' + preview_id).html(img_html)
    } else if (max_upload_count - uploaded_count > 0) {
        // 多图上传
        $('#' + preview_id).append(img_html)
    }
}

/**
 * 图片上传（由is_single控制 多图/多图 上传，默认多图上传）
 * @param {string} file_id file上传按钮id
 * @param {string} imgs 图片id隐藏域
 * @param {string} preview_box 已上传图片预览盒子id
 * @param {boolean} is_cropper 是否是裁剪框中的预览图
 * @param {number} max_upload_count 最多上传图片数量
 * */
function uploadImage(file_id, imgs, preview_box, is_cropper = false, max_upload_count = 9) {
    // 已上传图片数量
    var uploaded_count = $('#' + preview_box).find('img').length;

    if (max_upload_count - uploaded_count > 0 || max_upload_count == 1) {
        var file_obj = document.querySelector('#' + file_id);
        file_obj.click();
        file_obj.addEventListener('change', function () {
            var pics = document.querySelector('#' + file_id).files;

            if (pics.length > 0) {
                for (var i = 0; i < pics.length; i++) {
                    if (max_upload_count - uploaded_count - i > 0 || max_upload_count == 1) {
                        var formData = new FormData();
                        var url = "/upload/UploadFile/uploadPicture";
                        formData.append('download', pics[i]);
                        $.ajax({
                            url: url,
                            type: "post",
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            success: function (data) {
                                if (data.status == 1) {

                                    var img_ids = $('#' + imgs).val();

                                    //上传成功
                                    var id = data.data.id;
                                    var path = data.data.path;

                                    renderPreviewImg(id, path, preview_box, is_cropper, max_upload_count);

                                    if (max_upload_count == 1) {
                                        // 单图上传
                                        $('#' + imgs).val(id);
                                    } else {
                                        // 多图上传
                                        if (img_ids == '') {
                                            img_ids = id;
                                        } else {
                                            img_ids += ',' + id;
                                        }
                                        $('#' + imgs).val(img_ids)
                                    }
                                }
                            }
                        });
                    } else {
                        layer.msg('最多上传' + max_upload_count + '张图片');
                        break;
                    }
                }
                clearFile(file_id)
            }
        })
    } else {
        layer.msg('最多上传' + max_upload_count + '张图片');
    }

}

/**
 * 删除图片（新版本）
 * @param {elem} that this
 * @param {string} ids_str 图片id变量名
 * @param {string} paths_str 图片路径变量名
 * @param {string} prefix 前缀
 * */
function delImage(that, ids_str, paths_str, prefix) {
    var outer_obj = $(that).parent().parent().parent();
    var index = outer_obj.find('.' + prefix + 'uploaded-img-del').index(that);
    if (eval(ids_str).length > 0) {
        // 裁剪框删除图片

        eval(ids_str).splice(index, 1);
        eval(paths_str).splice(index, 1);
    } else {
        // form表单删除图片

        var hidden_input_obj = outer_obj.find('.hidden_value');
        // 已上传图片id集合
        var input_uploaded_img_ids = hidden_input_obj.val();
        if (input_uploaded_img_ids) {
            var input_uploaded_img_ids_arr = input_uploaded_img_ids.split(',');
            input_uploaded_img_ids_arr.splice(index, 1)
            hidden_input_obj.val(input_uploaded_img_ids_arr.join(','))
        }
    }

    $(that).parent().remove();
}